/**
 * 
 */
package com.application.Controller;

import it.unipr.ce.dsg.s2p.org.json.JSONObject;
import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import org.w3c.dom.Document;

import ReadWriteXML.CMember;
import ReadWriteXML.ReadXML;
import ReadWriteXML.WriteXML;
import android.R.array;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.util.Log;

import com.application.Activity.FrmChatGroup;
import com.application.Activity.FrmConversation;
import com.application.Activity.FrmDoTest;
import com.application.Activity.FrmSelectFile;
import com.application.Activity.FrmSubject;
import com.application.Activity.FrmTabActivity;
import com.application.Activity.MESApplication;
import com.application.Activity.R;
import com.application.Activity.frmBieuQuyetMoiRoiNhom;
import com.application.Activity.frmChatPeerActivity;
import com.application.Activity.frmMatKetNoiActivity;
import com.application.Activity.frmNhomChoActivity;
import com.application.Activity.frmNotificationMoiVaoNhom;
import com.application.Activity.frmPhuActivity;
import com.application.Activity.frmTreeNodeActivity;
import com.application.Activity.tabActivity;
import com.application.Activity.trucActivity;

/**
 * @author TAI
 * 
 */
public class ActivityController {
	//\\\\\\\\\\\\\\\\\\\\\\\
	public static ArrayList<Activity> arrActivity=new ArrayList<Activity>();
	public static void addActivityToArray(Activity a){
		arrActivity.add(a);
	}
	public static Activity getActivityFromArray(){
		Activity kq=new Activity();
		kq=arrActivity.get(arrActivity.size()-1);
		return kq;
	}
	public static Activity getActivityPreviousFromArray(){
		Activity kq=new Activity();
		kq=arrActivity.get(arrActivity.size()-2);
		return kq;
	}
	
	public static void closeActivity(final Activity ac){
		handler.post(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				ac.finish();
			}
		});
	}
	public static void finishAllActivity(){
		ArrayList<Activity> arr=new ArrayList<Activity>();
		arr=arrActivity;
//		int i=arr.size();
//		while(i>0){
//			Activity a=new Activity();
//			a=arr.get(i);
//			closeActivity(a);
//			//arr.remove(i);
//		}
		
		int i=0;
		while(i<arr.size()){
			Activity a=new Activity();
			
			a=arr.get(i);
			Log.i("Phu","vao : "+a.getLocalClassName());
			closeActivity(a);
			i++;
			//arr.remove(i);
		}
	}
	//\\\\\\\\\\\\\\\\\\\\\\\
	public static int ON_EXIT_APP=1111;
	private static Activity peerActivity = null;
	final private static String SEPARATOR = "/";
	public static Handler handler = new Handler();
	
	// ====TRUC============
	private static ArrayList<ArrayList<String>> arraylist;
	private static int _countdg = 0;
	private static int _valueAgree = 0;
	private static int _valueDisAgree = 0;
	private static int _count = 0;

	private static int _index = 0;

	// public static String mess;

	public static void showGroupInvite() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				frmPhuActivity.show("Co nguoi moi ban vao nhom");

			}
		});
	}

	public static void ReLoadTabTree() {
		handler.post(FrmTabActivity.reLoadTabTree);
	}

	public static void showMessageTeacherLogout() {
		handler.post(FrmTabActivity.raShowTeacherLogout);
	}

	public static void showMoiVaoNhomNotification(String groupName, String msg) {
		FrmTabActivity.contentText = groupName;
		FrmTabActivity.contentTitle = msg;
		handler.post(FrmTabActivity.raMoiVaoNhomNotif);
	}

	public static void showNotification(String title, String contentTitle, String contentText) {
		Intent intent = new Intent(peerActivity, frmNotificationMoiVaoNhom.class);
		intent.putExtra("ID", 1);
		PendingIntent pendingIntent = PendingIntent.getActivity(peerActivity, 0, intent, 0);
		NotificationManager notiManager = (NotificationManager) peerActivity.getSystemService(peerActivity
				.getBaseContext().NOTIFICATION_SERVICE);
		Notification notif = new Notification(R.drawable.ic_launcher, title, System.currentTimeMillis());
		notif.setLatestEventInfo(peerActivity, contentTitle, contentText, pendingIntent);

		notiManager.notify(1, notif);

	}

	public static void showNhomChoActivity() {
		// Intent i=new Intent()
	}

	public static void startGroup() {
		handler.post(frmNhomChoActivity.raStartGroup);

	}

	public static void showMatKetNoi() {
		// Intent intent = new Intent(MESApplication.getAppContext(),
		// frmMatKetNoiActivity.class);
		// if (!frmMatKetNoiActivity.isShowed) {
		// MESApplication.getAppContext().startActivity(intent);
		// }

	}

	public static void closeMatKetNoi() {
		handler.post(frmMatKetNoiActivity.raClose);
	}

	// =============================================truc==================================

	public static void ShowMessageOnTree(final String message) {
		frmTreeNodeActivity.message = message;
		handler.post(frmTreeNodeActivity.raShowMessage);
	}

	public static void ShowMessageTAB(final String message) {
		FrmTabActivity.message = message;
		handler.post(FrmTabActivity.showMessage);
	}

	public static void ShowMessage(final String message) {
		trucActivity.message = message;
		handler.post(trucActivity.showMessage);
	}

	// hien thi noi dung chat

	public static void ShowChatMessage(final String message, final String address) {
		trucActivity.chatMessage = message;
		trucActivity.addressFriend = address;
		handler.post(trucActivity.showChatMessage);
	}

	public static void DislayKickMember() {
		handler.post(FrmTabActivity.dislayKickMember);

	}

	public static void ShowResultVote() {
		// handler.post(FrmTabActivity.showResultVoteKick);
	}

	public static void FinishDiscussActivity() {
		// handler.post(FrmTabActivity.finishAct);
	}

	public static void DoEndTime() {
		handler.post(frmBieuQuyetMoiRoiNhom.doEndTime);
	}

	// public static void HienThiTinNhanChatRieng(){
	// hander.post(frmChatPeerActivity.showMessageChat);
	// }

	// chat rieng

	public static void updateMessageChatPeer(final String ipReceiver, final String userName) {
		frmChatPeerActivity._IPFriend = ipReceiver;
		frmChatPeerActivity._userNameFriend = userName;
		frmChatPeerActivity._FriendChatting = userName;
		// frmChatPeerActivity.updateMessage();=====================================================
	}

	public static void ShowChatPeer(final String ipReceiver, final String userName) {
		FrmTabActivity.ipSender = ipReceiver;
		FrmTabActivity.userNameSender = userName;
		handler.post(FrmTabActivity.showFormChatPeer);
	}

	public static void FinishChatPeerActivity() {
		handler.post(frmChatPeerActivity.closeMyForm);
	}

	public static void ShowChatPeerNonParamater() {

		handler.post(trucActivity.showFormChatPeer);
	}

	public static void ShowChatConversation() {
		handler.post(trucActivity.showFormConversation);
	}

	// end chat rieng
	// ===============================end truc=================================

	public static void ShowAlert(Context context, String title, String message, int icon) {
		AlertDialog.Builder buider = new Builder(context);
		buider.setTitle(title);
		buider.setMessage(message);
		buider.setIcon(icon);
		buider.setNegativeButton("OK", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub

			}
		});
		buider.show();
	}

	// **********
	// ====An
	// **********
	public static void show_Error() {
		trucActivity.show("Ban khong co quyen nay");
	}

	public static void ShowSignOut(String name) {
		Log.d("PEERDROID", "vao show sign out: " + name);
		// hander.post(trucActivity.raSignout);
		trucActivity.showSignOut(name);
	}

	public static void ShowDanhGia(Address sender) {
		Log.d("PEERDROID", "vao show danh gia");
		// hander.post(trucActivity.raShowDanhGia);
		trucActivity.showRequestDanhGia(sender);
	}

	// Ham Tinh ket qua Danh Gia
	public static void CountResultDanhGia(String result) {
		Log.d("PEERDROID", "Ket qua da nhan duoc: " + result);
		String[] s = result.split(";");
		String[] d = null;
		ArrayList<String> array;
		_countdg++;
		if (arraylist == null) {
			Log.d("PEERDROID", "arraylist null ");
			arraylist = new ArrayList<ArrayList<String>>();
			for (int i = 0; i < s.length; i++) {

				array = new ArrayList<String>();
				Log.d("PEERDROID", "s: " + s[i].toString());
				d = s[i].split("/");
				int j = 0;
				while (j < 2) {

					array.add(d[j].toString());
					j++;
				}
				arraylist.add(array);

				Log.d("PEERDROID", "arraylist get : " + arraylist.get(i));
			}
		} else {
			Log.d("PEERDROID", "arraylist not null ");
			for (int i = 0; i < s.length; i++) {

				array = new ArrayList<String>();
				Log.d("PEERDROID", "s: " + s[i].toString());
				d = s[i].split("/");
				int j = 0;
				while (j < 2) {

					array.add(d[j].toString());
					j++;
				}
				for (int k = 0; k < arraylist.size(); k++) {
					Log.d("PEERDROID", "i =  " + String.valueOf(k));
					Log.d("PEERDROID", "vao vong lap For arraylist " + arraylist.get(k).get(0));
					Log.d("PEERDROID", "array.get(0) " + array.get(0));

					if (arraylist.get(k).get(0).equals(array.get(0))) {

						Log.d("PEERDROID", "vao vong lap For arraylist ->> if ");

						float point = Float.parseFloat(arraylist.get(k).get(1));
						Log.d("PEERDROID", "point : " + String.valueOf(point));

						float pointnew = Float.parseFloat(array.get(1));
						Log.d("PEERDROID", "point new: " + String.valueOf(pointnew));

						point += pointnew;
						Log.d("PEERDROID", "point updated: " + String.valueOf(point));

						String p = String.valueOf(point);
						Log.d("PEERDROID", " arraylist get k " + arraylist.get(k));

						arraylist.get(k).add(1, p);
						Log.d("PEERDROID", " arraylist get last " + arraylist.get(k));
					} else {
						Log.d("PEERDROID", "sai bet: ");
					}
				}
			}
		}
	}

	// Ham tinh ket qua Bieu Quyet
	public static void CountResultBieuQuyet(int index, int value) {
		Log.d("PEERDROID", "Ket qua bieu quyet nhan duoc: " + String.valueOf(index) + "-" + String.valueOf(value));
		_count++;
		_index = index;
		if (value == 0) {
			if (_valueDisAgree == 0) {
				_valueDisAgree++;
			} else {
				_valueDisAgree += 1;
			}
		} else {
			if (value == 1 && _valueAgree == 0) {
				_valueAgree++;
			} else {
				_valueAgree += 1;
			}
		}
	}

	public static void WriteTextToLog(String text, String name) {
		Log.d("Phu", "Da vào WriteTextToLog trong ActivityController");
		Log.d("Phu", NetworkController._peer.getAccount().get_Username() + "-" + text);
		// String username =
		// NetworkController._peer.getAccount().get_Username();
		String tenNhom = NetworkController.getGroupName();
		Log.d("Phu", "ten nhom 2....: " + tenNhom);
		String path = ReadWriteFileController.DIRECTORY + tenNhom + "LogList.xml";
		Log.d("Phu", "Path: " + path);
		ReadWriteFileController.insertLogFile(path, text, name);
	}

	public static int get_countdg() {
		return _countdg;
	}

	public static void set_countdg(int _countdg) {
		ActivityController._countdg = _countdg;
	}

	public static ArrayList<ArrayList<String>> getArraylist() {
		return arraylist;
	}

	public static void setArraylist(ArrayList<ArrayList<String>> arraylist) {
		ActivityController.arraylist = arraylist;
	}

	public static int get_valueAgree() {
		return _valueAgree;
	}

	public static void set_valueAgree(int _valueAgree) {
		ActivityController._valueAgree = _valueAgree;
	}

	public static int get_valueDisAgree() {
		return _valueDisAgree;
	}

	public static void set_valueDisAgree(int _valueDisAgree) {
		ActivityController._valueDisAgree = _valueDisAgree;
	}

	public static int get_count() {
		return _count;
	}

	public static void set_count(int _count) {
		ActivityController._count = _count;
	}

	public static int get_index() {
		return _index;
	}

	public static void set_index(int _index) {
		ActivityController._index = _index;
	}

	// public static void AddNode(final int parentId,final Node node){
	// frmTreeNodeActivity.parentId=parentId;
	// frmTreeNodeActivity.nodeAdd=node;
	// hander.post(frmTreeNodeActivity.raAddnode);
	// }

	public static void ShowMessageKicked() {
		handler.post(FrmTabActivity.dislayKickedMessage);
	}

	// ====END TRUC=======

	/**
	 * Hiển thị Subject khi nhận được message get Subject
	 * 
	 * @param params
	 */
	public static void ShowSubject(JSONObject params) {
		getPeerActivity().startActivity(new Intent(getPeerActivity().getBaseContext(), FrmSubject.class));
	}

	/**
	 * Hiển thị Chapter khi nhận được message get chapter
	 * 
	 * @param params
	 */
	public static void ShowChapter(JSONObject params) {

	}

	/**
	 * Hiển thị Part khi nhận message get Part
	 * 
	 * @param params
	 */
	public static void ShowPart(JSONObject params) {

	}

	/**
	 * Hiển thị DetailLearning khi nhận message get DetailLearning
	 * 
	 * @param params
	 */
	public static void ShowDetailLearning(JSONObject params) {

	}

	public static void updateListUser() {
		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				FrmChatGroup.updateListUser();
			}
		});

	}

	public static void ShowDialogDuplicateAccount() {
		handler.post(new Runnable() {
			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(peerActivity);
				builder.setIcon(R.drawable.img_dialog);
				builder.setMessage("Có một học viên nào đó đã đăng nhập bằng tài khoản của bạn!").setCancelable(false)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {

								Log.d("PEERDROID", "Đã Thoát khỏi chương trình");
								NetworkController.peerRelease();
								peerActivity.finish();
								System.exit(0);
							}
						});
				AlertDialog alert = builder.create();
				alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
				alert.show();
			}
		});

	}

	
	public static void ShowDialogTeacherLogout() {
		Log.v("Phu","vao ham ShowDialogTeacherLogout activityControl");
		//Log.e("Phu", "activity = "+peerActivity.getCallingActivity().toShortString());
		Log.e("Phu", "activity class = "+peerActivity.getLocalClassName());
		//Log.e("Phu", "activity text = "+peerActivity.getText(0));
		
		
		handler.post(new Runnable() {
			@Override
			public void run() {
				
				AlertDialog dlg = new AlertDialog.Builder(peerActivity).setTitle("Thông báo")
				.setCancelable(false).setMessage("Giáo viên đã rời khỏi hệ thống.")//.setIcon(R.drawable.img_dialog)
				
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.v("Phu","vao onclick");
						NetworkController.peerRelease();
						Activity before=getActivityPreviousFromArray();
						Log.e("Phu","activity truoc = "+before.getLocalClassName());
						
						Log.d("Phu", "set result");
						//	Intent i=new Intent(peerActivity, FrmTabActivity.class);
							
						//	peerActivity.setResult(ON_EXIT_APP);
						//	peerActivity.startActivityForResult(i, ON_EXIT_APP);
							peerActivity.setResult(FrmTabActivity.ON_EXIT_APP);
							//closeActivity(before);
							finishAllActivity();
							Log.v("PEERDROID","Đã Thoát khỏi chương trình");
							peerActivity.finish();
							
					}
				}).create();
				Log.v("Phu","1");
				dlg.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
				Log.v("Phu","2");
				dlg.show();
				
				Log.v("Phu","3");
			}
		});

	}

	public static void ShowNotification(JSONObject params, int type, int i) {
		// NotificationController nc = new NotificationController();
		// nc.startService(new
		// Intent(getPeerActivity().getBaseContext(),NotificationController.class));

		switch (i) {
		case 1: // show dotest
		{
			// ShowActivityDoTest(params, type);
			ArrayList<Integer> res = new ArrayList<Integer>();
			res = ReadWriteFileController.WriteTest(params, type);
			Log.d("PEERDROID", "Res nhan bai tap " + res.toString());
			if (res.size() == 3)// có cả part và detailLearning
			{
				String fQues = res.get(0) + "_" + res.get(1) + "_FullTest_" + res.get(2);
				FrmDoTest.set_fNameQues(fQues);
				NotificationController.sendNotification(getPeerActivity().getBaseContext(), FrmDoTest.class,
						"Thông báo", "Có bài tập", Notification.DEFAULT_SOUND);
			}
			break;
		}

			// case 2://show resultAnswer
			// {
			// String s=null;
			// Iterator<String> iter = params.keys();
			// while(iter.hasNext()){
			// String key = iter.next();
			// if(key.contains("tk"))
			// {
			// try {
			// s = params.getString(key);
			// FrmResultAnswer.set_result(s);
			// } catch (JSONException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// }
			// }
			// handler.post(new Runnable() {
			//
			// @Override
			// public void run() {
			// // TODO Auto-generated method stub
			// FrmPart.updateListAdapter();
			// }
			// });
			// NotificationController.sendNotification(getPeerActivity().getBaseContext(),
			// FrmResultAnswer.class, "Thông báo", "Xem kết quả",
			// Notification.DEFAULT_SOUND);
			// break;
			// }
		}
	}

	public static void ShowDialogReceiveReInvite(String fullName) {
		final String name = fullName;
		handler.post(new Runnable() {
			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(peerActivity);
				builder.setIcon(R.drawable.img_dialog);
				builder.setMessage(name + " không đồng ý vào nhóm của bạn").setCancelable(false)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								Log.d("PEERDROID", "xác nhận có người vô nhóm");
							}
						});
				AlertDialog alert = builder.create();
				alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
				alert.show();
			}
		});

	}

	// public static void ShowDialogReceiveInviteExit(String fullName, String
	// userName)
	// {
	// final String fullnamecreater = fullName;
	// final String usernamecreater = userName;
	// handler.post(new Runnable() {
	// @Override
	// public void run() {
	// AlertDialog.Builder builder = new AlertDialog.Builder(peerActivity);
	// builder.setIcon(R.drawable.img_dialog);
	// builder.setMessage(fullnamecreater + "đã giải tán nhóm!")
	// .setCancelable(false)
	// .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	// @Override
	// public void onClick(DialogInterface dialog, int id) {
	// Log.d("PEERDROID","xóa danh sách nhóm");
	// String path = ReadWriteFileController.DIRECTORY + "Group_" +
	// fullnamecreater + "_ipList";
	// ReadWriteFileController.deleteFile(path);
	// //cập nhật thông tin giao diện:
	// //nếu không ở from hiện hành --> xóa trong conversation
	// handler.post(new Runnable() {
	//
	// @Override
	// public void run() {
	// // TODO Auto-generated method stub
	// ViewConversation view = new ViewConversation(usernamecreater, "",2, "",
	// "");
	// FrmConversation.deleteViewConversationItem(view);
	// }
	// });
	// //nếu ở from hiện hành --> finish(), xóa trong conversation
	//
	// }
	// });
	// AlertDialog alert = builder.create();
	// alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0,
	// 255, 255, 255)));
	// alert.show();
	// }
	// });
	//
	// }
	public static void ShowDialogReceiveInvite(Address addr, String name, String userName, String info) {
		Log.d("PEERDROID", "nameinvite: " + name);
		Log.d("PEERDROID", "userNameInvite: " + userName);
		final String address = addr.getHost() + ":" + addr.getPort();
		Log.d("PEERDROID", "address: " + address);
		final String fullNameInvite = name;
		final String userNameInvite = userName;
		final String infoText = info;
		handler.post(new Runnable() {
			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(peerActivity);
				builder.setIcon(R.drawable.img_dialog);
				String mess = null;
				if (infoText.equals(""))
					mess = "Bạn được mời vào nhóm của " + fullNameInvite;
				else
					mess = "Bạn được mời vào nhóm của " + fullNameInvite + "\n" + infoText;
				builder.setMessage(mess).setCancelable(false)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								Log.d("PEERDROID", "đồng ý vào nhóm");
								// gui thong tin dong y cho ben kia.
								NetworkController.SendReInvite(new Address(address), 1,
										NetworkController.get_userName(), NetworkController.get_fullName(),
										userNameInvite);
								ArrayList<Object> message = new ArrayList<Object>();
								message.add(userNameInvite);
								message.add("");
								message.add(2);
								message.add(address);
								message.add(fullNameInvite);

								CMember mem = new CMember(address, fullNameInvite, userNameInvite);
								// lưu xuống xml danh sách nhóm
								Document doc = null;
								String path = ReadWriteFileController.DIRECTORYCHATGROUP + "Group_" + userNameInvite
										+ "_ipList.xml";
								if (!ReadWriteFileController.isFile(path))
									doc = WriteXML.insertRoot(doc, path, "ListLearner");
								doc = ReadXML.BuildXML(path);

								// insert người mời vào ds group
								if (!ReadWriteFileController.isExistUserName(path, userNameInvite))
									doc = WriteXML.insertMember(doc, path, mem);

								// insert chính mình vào ds group
								mem = new CMember(NetworkController.get_ipUser(), NetworkController.get_fullName(),
										NetworkController.get_userName());
								if (!ReadWriteFileController.isExistUserName(path, NetworkController.get_userName()))
									doc = WriteXML.insertMember(doc, path, mem);
								FrmConversation.receiveMessage(message);
							}
						}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {

								Log.d("PEERDROID", "không đồng ý vào nhóm");
								// gui thong tin dong y cho ben kia.
								NetworkController.SendReInvite(new Address(address), 0,
										NetworkController.get_userName(), NetworkController.get_fullName(),
										userNameInvite);
							}
						});
				AlertDialog alert = builder.create();
				alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
				alert.show();
			}
		});

	}

	public static void ShowDialogReceiveFile(Address addr, String userName, String fullName, String type,
			String keychat, String fName, String portNumber) {
		final String sfullname = fullName;
		final String suserName = userName;
		final String address = addr.getHost();
		final String stype = type;
		final String skeychat = keychat;
		final String sfName = fName;
		final int iport = Integer.valueOf(portNumber);
		handler.post(new Runnable() {
			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(peerActivity);
				builder.setIcon(R.drawable.img_dialog);
				String mess = "Bạn nhận được một tập tin từ " + sfullname;
				builder.setMessage(mess).setCancelable(false)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								// link đến đường dẫn lưu file
								Intent intent = new Intent(peerActivity.getBaseContext(), FrmSelectFile.class);
								intent.putExtra(FrmSelectFile.START_PATH, "/sdcard");
								peerActivity.startActivityForResult(intent, 1);
								// mở socket, lấy file
								ThreadReceiveFile thread = new ThreadReceiveFile();
								thread.SetReceive(sfName, address, iport);
								thread.start();
							}
						}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								Log.d("PEERDROID", "không đồng ý vào nhóm");
							}
						});
				AlertDialog alert = builder.create();
				alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
				alert.show();
			}
		});

	}

	private static String getMessage(String[] temp) {
		String result = "";
		// i chay tu 2 đe lay ra message
		for (int i = 2; i < temp.length; i++) {
			if (i == temp.length - 1) {
				result = result + temp[i];
			} else {
				result = result + temp[i] + "/";
			}
		}
		return result;
	}

	/**
	 * 
	 * @param temp
	 * @return
	 */
	private static String getMessageGroup(String[] temp) {
		String result = "";
		// i chay tu 2 đe lay ra message
		for (int i = 1; i < temp.length; i++) {
			if (i == temp.length - 1) {
				result = result + temp[i];
			} else {
				result = result + temp[i] + "/";
			}
		}
		return result;
	}

	public static void setPeerActivity(Activity peerActivity) {
		ActivityController.peerActivity = peerActivity;
	}

	public static Activity getPeerActivity() {
		return peerActivity;
	}

	public static void ShowDialogReceiveGroupInvite(int nummember, long closegroup, long time) {
		Log.d("PEERDROID", "nummember: " + nummember);
		Log.d("PEERDROID", "thời gian chốt: " + closegroup);
		Log.d("PEERDROID", "thời gian tồn tại group: " + time);
		final int soluong = nummember;
		final long thoigian = closegroup / 60;
		final String closeTime = ReadWriteFileController.ConvertTimeToString(time);
		handler.post(new Runnable() {
			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(peerActivity);
				builder.setIcon(R.drawable.img_dialog);
				String mess = "Yêu cầu lập nhóm làm bài tập nhóm.\n" + "Nhóm có tối đa " + soluong + " thành viên\n"
						+ "Lập nhóm trong vòng " + thoigian + " phút \n" + "Thảo luận đến: " + closeTime
						+ ". \nLưu ý: Khi hết thời gian thảo luận sẽ không nhận bài tập nữa!";

				builder.setMessage(mess).setCancelable(false)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {

							}
						});

				AlertDialog alert = builder.create();
				alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
				alert.show();
			}
		});

	}

	public static void ShowDialogReceiveExercisesGroup(String title) {
		Log.d("PEERDROID", "Tên bài tập: " + title);

		handler.post(new Runnable() {
			@Override
			public void run() {
				AlertDialog.Builder builder = new AlertDialog.Builder(peerActivity);
				builder.setIcon(R.drawable.img_dialog);
				String mess = "Bạn nhận được bài tập làm nhóm";

				builder.setMessage(mess).setCancelable(false)
						.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								Log.d("PEERDROID", "đồng ý làm bài tập nhóm");
								// gui thong tin dong y cho ben kia.

							}
						});

				AlertDialog alert = builder.create();
				alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
				alert.show();
			}
		});

	}
}
